package org.dromara.oce.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.oce.domain.OceAdvertiserReferralRelation;
import org.dromara.oce.domain.OcePromotionAddEverydayCensus;
import org.dromara.oce.domain.bo.OcePromotionAddEverydayCensusBo;
import org.dromara.oce.domain.dto.GetPromotionNumDTO;
import org.dromara.oce.domain.vo.OcePromotionAddEverydayCensusVo;
import org.dromara.oce.mapper.OcePromotionAddEverydayCensusMapper;
import org.dromara.oce.service.OcePromotionAddEverydayCensusService;
import org.dromara.oce.service.remote.OceanEngineRemoteService;
import org.dromara.system.domain.SysDept;
import org.dromara.system.mapper.SysDeptMapper;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 广告每日新增数量统计Service业务层处理
 *
 * @author Lion Li
 * @date 2024-12-24
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OcePromotionAddEverydayCensusServiceImpl extends ServiceImpl<OcePromotionAddEverydayCensusMapper, OcePromotionAddEverydayCensus> implements OcePromotionAddEverydayCensusService {

    private final OcePromotionAddEverydayCensusMapper baseMapper;
    private final SysDeptMapper deptMapper;
    private final OceanEngineRemoteService engineRemoteService;

    /**
     * 查询广告每日新增数量统计
     *
     * @param promotionAddCensusId 主键
     * @return 广告每日新增数量统计
     */
    @Override
    public OcePromotionAddEverydayCensusVo queryById(Long promotionAddCensusId) {
        return baseMapper.selectVoById(promotionAddCensusId);
    }

    /**
     * 分页查询广告每日新增数量统计列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 广告每日新增数量统计分页列表
     */
    @Override
    public TableDataInfo<OcePromotionAddEverydayCensusVo> queryPageList(OcePromotionAddEverydayCensusBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OcePromotionAddEverydayCensus> lqw = buildQueryWrapper(bo);
        Page<OcePromotionAddEverydayCensusVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的广告每日新增数量统计列表
     *
     * @param bo 查询条件
     * @return 广告每日新增数量统计列表
     */
    @Override
    public List<OcePromotionAddEverydayCensusVo> queryList(OcePromotionAddEverydayCensusBo bo) {
        LambdaQueryWrapper<OcePromotionAddEverydayCensus> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OcePromotionAddEverydayCensus> buildQueryWrapper(OcePromotionAddEverydayCensusBo bo) {
//        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OcePromotionAddEverydayCensus> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(OcePromotionAddEverydayCensus::getPromotionAddCensusId);
        lqw.eq(bo.getThatdayTimestamp() != null, OcePromotionAddEverydayCensus::getThatdayTimestamp, bo.getThatdayTimestamp());
        lqw.eq(StringUtils.isNotBlank(bo.getThatdayDate()), OcePromotionAddEverydayCensus::getThatdayDate, bo.getThatdayDate());
        lqw.like(StringUtils.isNotBlank(bo.getCreateName()), OcePromotionAddEverydayCensus::getCreateName, bo.getCreateName());
        lqw.eq(bo.getPromotionNum() != null, OcePromotionAddEverydayCensus::getPromotionNum, bo.getPromotionNum());
        if(StringUtils.isNotBlank(bo.getStartDate()) && StringUtils.isNotBlank(bo.getEndDate())){
            lqw.between(OcePromotionAddEverydayCensus::getThatdayDate,bo.getStartDate(),bo.getEndDate());
        }
        if(bo.getDeptId() != null){
            List<SysDept> deptList = deptMapper.selectListByParentId(bo.getDeptId());
            List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId);
            ids.add(bo.getDeptId());
            lqw.in(OcePromotionAddEverydayCensus::getDeptId, ids);
        }
        return lqw;
    }

    /**
     * 新增广告每日新增数量统计
     *
     * @param bo 广告每日新增数量统计
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OcePromotionAddEverydayCensusBo bo) {
        OcePromotionAddEverydayCensus add = MapstructUtils.convert(bo, OcePromotionAddEverydayCensus.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPromotionAddCensusId(add.getPromotionAddCensusId());
        }
        return flag;
    }

    /**
     * 修改广告每日新增数量统计
     *
     * @param bo 广告每日新增数量统计
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OcePromotionAddEverydayCensusBo bo) {
        OcePromotionAddEverydayCensus update = MapstructUtils.convert(bo, OcePromotionAddEverydayCensus.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OcePromotionAddEverydayCensus entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除广告每日新增数量统计信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void syncPromotionAddData(List<OceAdvertiserReferralRelation> batchList, String date, Long dateTimestamp) {
        List<OcePromotionAddEverydayCensus> listSave = new ArrayList<>();
        List<OcePromotionAddEverydayCensus> listUpdate = new ArrayList<>();
        List<GetPromotionNumDTO> promotionNums = new ArrayList<>();
        Map<String, Integer> map = new HashMap<>();
        Map<String, Long> mapDept = new HashMap<>();
        batchList.forEach(referralRelation -> {
            String createName = referralRelation.getCreateName().trim();
            Long deptId = referralRelation.getDeptId();
            if(!mapDept.containsKey(createName)){
                mapDept.put(createName, deptId);
            }
            MDC.put("appCode", referralRelation.getThirdAdvertiserAppCode());
            GetPromotionNumDTO promotion = engineRemoteService.getPromotionNum(referralRelation.getThirdAdvertiserId(), date);
            if (Objects.nonNull(promotion)) {
                promotion.setCreateName(createName);
                promotionNums.add(promotion);
            }
        });
        if (CollectionUtils.isNotEmpty(promotionNums)) {
            Map<String, List<GetPromotionNumDTO>> mapList = promotionNums.stream().collect(Collectors.groupingBy(GetPromotionNumDTO::getCreateName));
            for (Map.Entry<String, List<GetPromotionNumDTO>> entry : mapList.entrySet()) {
                String createName = entry.getKey();
                List<GetPromotionNumDTO> promotionNumList = entry.getValue();
                Integer promotionNum = promotionNumList.stream().map(GetPromotionNumDTO::getPromotionNum).filter(Objects::nonNull).reduce(0, Integer::sum);
                String key = GlobalConstants.GLOBAL_REDIS_KEY + "oce:promotionAddNum:" + createName;
                Integer promotionNumCache = RedisUtils.getCacheObject(key);
                if (Objects.isNull(promotionNumCache)) {
                    promotionNumCache = 0;
                }
                promotionNumCache += promotionNum;
                if (promotionNumCache > 0) {
                    RedisUtils.setCacheObject(key, promotionNumCache, Duration.ofMinutes(10L));
                }
                map.put(createName, promotionNumCache);
            }
        }
        if (CollectionUtils.isNotEmpty(map)) {
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                OcePromotionAddEverydayCensusBo bo = new OcePromotionAddEverydayCensusBo();
                bo.setCreateName(entry.getKey());
                bo.setThatdayTimestamp(dateTimestamp);
                LambdaQueryWrapper<OcePromotionAddEverydayCensus> lqw = buildQueryWrapper(bo);
                OcePromotionAddEverydayCensus oceMaterialEverydayCensus = baseMapper.selectOne(lqw);
                if (Objects.nonNull(oceMaterialEverydayCensus)) {
                    oceMaterialEverydayCensus.setPromotionNum(entry.getValue());
                    listUpdate.add(oceMaterialEverydayCensus);
                } else {
                    oceMaterialEverydayCensus = new OcePromotionAddEverydayCensus();
                    oceMaterialEverydayCensus.setCreateName(entry.getKey());
                    oceMaterialEverydayCensus.setPromotionNum(entry.getValue());
                    oceMaterialEverydayCensus.setThatdayDate(date);
                    oceMaterialEverydayCensus.setThatdayTimestamp(dateTimestamp);
                    oceMaterialEverydayCensus.setCreateTime(LocalDateTime.now());
                    oceMaterialEverydayCensus.setDeptId(mapDept.getOrDefault(entry.getKey(), 0L));
                    listSave.add(oceMaterialEverydayCensus);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(listSave)) {
            baseMapper.insertBatch(listSave);
        }
        if (CollectionUtils.isNotEmpty(listUpdate)) {
            baseMapper.updateBatchById(listUpdate);
        }
    }
}
